 package org.zlb.netty.client.rpc;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

import org.zlb.netty.dbo.RpcRequest;
import org.zlb.netty.dbo.RpcResponse;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;

public class RpcMessageClientHandler extends ChannelInboundHandlerAdapter {
    
    private ConcurrentMap<String, RpcResponseCallback> responseMap = new ConcurrentHashMap<String, RpcResponseCallback>();
    private volatile Channel channel;
    
    public ConcurrentMap<String, RpcResponseCallback> getResponseMap() {
        return responseMap;
    }
    
    public void send(RpcMessageClient client, RpcRequest req) throws InterruptedException {
        RpcResponseCallback callback = new RpcResponseCallback();
        responseMap.put(req.getRequestId(), callback);
        this.channel.writeAndFlush(req);
    }
    
    public RpcResponse response(RpcRequest req) throws InterruptedException {
        try {
            RpcResponseCallback callback = responseMap.get(req.getRequestId());
            return callback.getResponse();
        } finally {
            responseMap.remove(req.getRequestId());
        }
    }

    @Override
    public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
        super.channelRegistered(ctx);
        this.channel = ctx.channel();
    }
    
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("连接服务端成功");
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws InterruptedException {
        if (msg instanceof RpcResponse) {
            RpcResponse resp = (RpcResponse)msg;
            RpcResponseCallback callback = responseMap.get(resp.getRequestId());
            callback.setResponse(resp);
            callback.setSuccess(true);
        }
    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if (evt instanceof IdleStateEvent) {
            IdleState state = ((IdleStateEvent) evt).state();
            if (state == IdleState.READER_IDLE) {
                
            } else if (state == IdleState.WRITER_IDLE) {
                
            } else {
                
            } 
        } else {
            super.userEventTriggered(ctx, evt);
        }
    }

}
